<template>
  <view>
    <view class="fab-container">
      <view class="fab" @click="openPopup">
        <up-icon name="grid" size="24" color="#fff"></up-icon>
      </view>
    </view>
    <up-popup
      :show="showPopup"
      mode="right"
      @close="closePopup"
      @open="openPopup">
      <view class="drawer-content">
        <u-status-bar></u-status-bar>
        <view class="drawer-title">快速检索</view>
        <view class="search-box">
          <up-search
            v-model="searchKeyword"
            placeholder="搜索文章"
            @custom="handleSearch"></up-search>
        </view>
        <view class="filter-section">
          <text class="filter-title">标签筛选</text>
          <view class="tags-container">
            <up-tag
              v-for="(tag, index) in filterTags"
              :key="tag.value"
              :text="tag.label"
              :plain="!selectedTags.includes(tag.value)"
              type="primary"
              @click="toggleTag(tag.value)"
              class="filter-tag"></up-tag>
          </view>
        </view>
        <view class="filter-section">
          <text class="filter-title">排序方式</text>
          <up-radio-group v-model="sortType" placement="row">
            <up-radio
              v-for="(item, index) in sortOptions"
              activeColor="green"
              :label="item.text"
              :name="item.value"
              :key="index"></up-radio>
          </up-radio-group>
        </view>
        <view class="filter-buttons">
          <button type="primary" @click="applyFilters">应用筛选</button>
          <button type="default" @click="resetFilters">重置</button>
        </view>
      </view>
    </up-popup>
    <base-page-container activeTab="list">
      <template #header>
        <view class="header">
          <u-status-bar></u-status-bar>
          <view class="header-content">
            <text class="title">中草药科普文章</text>
          </view>
        </view>
      </template>
      <template #content>
        <scroll-view
          class="article-list"
          scroll-y
          @scrolltolower="loadMore"
          refresher-enabled
          :refresher-triggered="isRefreshing"
          @refresherrefresh="onRefresh">
          <view
            class="article-item"
            v-for="(item, index) in articles"
            :key="index"
            @click="viewDetail(item.id)">
            <image
              class="article-image"
              :src="viewImg(item.cover)"
              mode="aspectFill"></image>
            <view class="article-content">
              <text class="article-title">{{ item.title }}</text>
              <view class="article-desc text-overflow-2">{{ item.description }}</view>
              <view class="article-meta">
                <text class="article-date">
                  {{ formatTime(item.createTime) }}
                </text>
                <view class="article-tags">
                  <up-tag
                    v-for="(tag, tagIndex) in item.tags"
                    :key="tagIndex"
                    :text="tag.label"
                    type="primary"
                    size="mini"></up-tag>
                </view>
              </view>
            </view>
          </view>
          <up-loadmore :status="loadMoreStatus" loading-text="加载中..." />
        </scroll-view>
      </template>
    </base-page-container>
  </view>
</template>
<script setup>
import { onMounted } from "vue";
import { getArticle_api, getArticleTag_api } from "@/api/api";
import { viewImg } from "@/utils/image";
import { formatTime } from "@/utils/format";

const pageParams = ref({
  pageNo: 1,
  pageSize: 5,
  params: {},
});
const searchKeyword = ref("");
const selectedTags = ref([]);
const sortType = ref("time");
const isRefreshing = ref(false);
const loadMoreStatus = ref("more");
const filterTags = [];
const sortOptions = [
  { value: "time", text: "最新发布" },
  { value: "hot", text: "最多阅读" },
  { value: "collect", text: "最多收藏" },
];
const articles = ref([]);
const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag);
  if (index === -1) {
    selectedTags.value.push(tag);
  } else {
    selectedTags.value.splice(index, 1);
  }
};
const handleSearch = async () => {
  pageParams.value.params = {
    title: searchKeyword.value,
  };
  await getArticleData();
  closePopup();
  searchKeyword.value = "";
};
const applyFilters = async () => {
  pageParams.value.params = {
    title: searchKeyword.value,
    tagIds: selectedTags.value.join(","),
  };
  await getArticleData();
  sortArticles();
  closePopup();
};
const sortArticles = () => {
  // 根据不同的排序方式对文章进行排序
  switch (sortType.value) {
    case "time":
      articles.value.sort((a, b) => b.createTime - a.createTime);
      break;
    case "hot":
      articles.value.sort((a, b) => b.pageView - a.pageView);
      break;
    case "collect":
      articles.value.sort((a, b) => b.collectCount - a.collectCount);
  }
};
const resetFilters = () => {
  searchKeyword.value = "";
  selectedTags.value = [];
  sortType.value = "";
};
const loadMore = async () => {
  // 检查是否还有更多数据可加载
  if (loadMoreStatus.value === "more") {
    loadMoreStatus.value = "loading";
    pageParams.value.pageNo++;
    try {
      const res = await getArticle_api(pageParams.value);
      // 将新数据追加到原有数据后面
      articles.value = [...articles.value, ...res.data.records];

      // 判断是否还有更多数据
      if (articles.value.length >= res.data.total) {
        loadMoreStatus.value = "noMore";
      } else {
        loadMoreStatus.value = "more";
      }
    } catch (error) {
      console.error("加载更多数据出错:", error);
      loadMoreStatus.value = "error";
      pageParams.value.pageNo--; // 回退页码
    }
  }
};

const onRefresh = async () => {
  isRefreshing.value = true;
  pageParams.value.pageNo = 1;
  await getArticleData();
  isRefreshing.value = false;
  loadMoreStatus.value = "more";
};

const viewDetail = (id) => {
  uni.navigateTo({
    url: "/subPackages/article/detail?id=" + id,
  });
};

/**
 * popup弹窗逻辑
 */
const showPopup = ref(false);
const closePopup = () => {
  showPopup.value = false;
};
const openPopup = () => {
  showPopup.value = true;
};

const getArticleTag = async () => {
  const res = await getArticleTag_api();
  filterTags.push(...res.data);
};

const getArticleData = async () => {
  const res = await getArticle_api(pageParams.value);
  articles.value = res.data.records;
};

onMounted(async () => {
  await getArticleTag();
  await getArticleData();
});
</script>
<style lang="scss" scoped>
.header {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  backdrop-filter: blur(20rpx);
  padding: 40rpx 30rpx;
  width: 100%;
  background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
  box-shadow: 0 8rpx 24rpx rgba(46, 125, 50, 0.15);
  transition: all 0.3s ease;
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.title {
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
  letter-spacing: 1.5px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.article-list {
  height: calc(100vh - 260rpx);
  overflow-y: auto;
  padding: 50rpx 30rpx;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.article-item {
  margin-bottom: 40rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
  transform: translateY(0);
  transition: all 0.3s ease;
  display: flex;
  height: 320rpx;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.article-item:active {
  transform: translateY(4rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.article-image {
  width: 280rpx;
  height: 100%;
  flex-shrink: 0;
  position: relative;
  transition: transform 0.3s ease;
}

.article-content {
  padding: 30rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.article-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  line-height: 1.4;
  height: 50rpx;
}

.article-desc {
  font-size: 15px;
  color: #5d6d7e;
  line-height: 1.6;
  margin-bottom: 20rpx;
}

.article-meta {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.article-date {
  font-size: 14px;
  color: #95a5a6;
  display: flex;
  align-items: center;
}

.article-date::before {
  content: "";
  display: inline-block;
  width: 6rpx;
  height: 6rpx;
  background-color: #4caf50;
  border-radius: 50%;
  margin-right: 12rpx;
  box-shadow: 0 0 4rpx rgba(76, 175, 80, 0.4);
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.drawer-content {
  width: 600rpx;
  padding: 40rpx 30rpx;
  background: linear-gradient(to bottom, #ffffff, #f8f9fa);
  height: 100%;
  box-sizing: border-box;
}

.drawer-title {
  font-size: 38rpx;
  color: #2c3e50;
  font-weight: bold;
  margin-bottom: 30rpx;
  letter-spacing: 1px;
}

.search-box {
  margin-bottom: 50rpx;
  padding: 24rpx;
  background-color: #ffffff;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  border-radius: 16rpx;
  overflow: hidden;
  transition: all 0.3s ease;
}

.filter-section {
  margin-bottom: 50rpx;
  padding: 34rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);
  transition: all 0.3s ease;
}

.filter-title {
  font-size: 17px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 34rpx;
  display: block;
  position: relative;
  padding-left: 28rpx;
}

.filter-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 6rpx;
  width: 8rpx;
  height: 28rpx;
  background-color: #4caf50;
  border-radius: 4rpx;
  box-shadow: 0 0 8rpx rgba(76, 175, 80, 0.4);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
  margin-bottom: 30rpx;
  padding: 10rpx 0;
}

.filter-tag {
  transition: all 0.3s ease;
  transform: scale(1);
}

.filter-tag:active {
  transform: scale(0.95);
}

.filter-buttons {
  display: flex;
  gap: 30rpx;
  margin-top: 60rpx;
  padding: 0 30rpx;
  box-sizing: border-box;

  button {
    width: 100%;
    height: 80rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 40rpx;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s ease;

    &[type="primary"] {
      background: linear-gradient(135deg, #4caf50, #2e7d32);
      box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
    }

    &[type="default"] {
      background: #f5f7fa;
      color: #7f8c8d;
      border: 1px solid #e0e6ed;
    }

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
    }
  }
}

.fab-container {
  position: fixed;
  bottom: 300rpx;
  right: 30rpx;
  width: 120rpx;
  height: 120rpx;
  z-index: 999;
}

.fab {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #4caf50, #2e7d32);
  color: white;
  border: none;
  border-radius: 50%;
  box-shadow: 0 4rpx 16rpx rgba(76, 175, 80, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.2);
  }
}
</style>
